from rest_framework import serializers
from corporateRecruitment import models
from jobs.jobsSer import JobSerializer


class CorporateSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.recruiterManagement
        fields = '__all__'


class CorporatePositionSerializer(serializers.ModelSerializer):
    position = JobSerializer(many=False)

    class Meta:
        model = models.recruiterManagement
        fields = '__all__'


class JobRecruiterSerializer(serializers.ModelSerializer):
    recruitermanagement_name = serializers.CharField(source='recruitermanagement.name', read_only=True)
    position_name = serializers.CharField(source='position.name', read_only=True)

    class Meta:
        model = models.jobRecruiter
        fields = '__all__'


class JobCategorySerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()  # 嵌套子分类

    def get_children(self, obj, depth=1):
        """
        1. 复用预加载的子分类数据，不执行新查询
        2. depth控制递归深度（默认1级子分类，最多3级）
        """
        # 限制递归深度，避免无限递归（可根据业务调整，比如改为5）
        if depth > 5:
            return []
        # 从预加载的反向关联中获取子分类，无额外SQL
        children = obj.jobcategory_set.all()
        # 递归序列化子分类，深度+1
        return JobCategorySerializer(children, many=True, context=self.context).data

    class Meta:
        model = models.jobCategory
        fields = '__all__'  # 或指定字段：['id', 'category_code', 'name', 'parent', 'children']
